package org.jeecg.modules.gzgl.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhaodui.fxy.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.gzgl.entity.*;
import org.jeecg.modules.gzgl.service.IFxyGzgl04Service;
import org.jeecg.modules.gzgl.service.IFxyGzgl09Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.gzgl.service.IFxyGzgl10Service;
import org.jeecg.modules.system.service.impl.SysDataLogServiceImpl;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 送达地址
 * @Author: zhaodui
 * @Date:   2020-02-06
 * @Version: V1.0
 */
@RestController
@RequestMapping("/gzgl/fxyGzgl09")
@Slf4j
public class FxyGzgl09Controller extends JeecgController<FxyGzgl09, IFxyGzgl09Service> {
	@Autowired
	private IFxyGzgl09Service fxyGzgl09Service;
	 @Autowired
	 private RedisUtil redisUtil;
	 @Autowired
	 private SysDataLogServiceImpl sysDataLogService;
	 @Autowired
	 private IFxyGzgl10Service fxyGzgl10Service;
	 @Autowired
	 private FxyGzgl04Controller fxyGzgl04Controller;
	 @Autowired
	 private IFxyGzgl04Service fxyGzgl04Service;
	 @Value(value = "${baseorg.common.appcode}")
	 private String appcode;
	/**
	 * 分页列表查询
	 *
	 * @param fxyGzgl09
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(FxyGzgl09 fxyGzgl09,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FxyGzgl09> queryWrapper = QueryGenerator.initQueryWrapper(fxyGzgl09, req.getParameterMap());
		Page<FxyGzgl09> page = new Page<FxyGzgl09>(pageNo, pageSize);
		IPage<FxyGzgl09> pageList = fxyGzgl09Service.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param fxyGzgl09
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FxyGzgl09 fxyGzgl09) {
		if(StringUtil.isEmpty(fxyGzgl09.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl09.getQuery39())) {//不提交法信
			fxyGzgl09Service.save(fxyGzgl09);
			return Result.ok("添加成功！");
		}
		String appCode = appcode;
			try {

				fxyUser fxyUser = new fxyUser();
				fxyUser.setUserId(fxyGzgl09.getQuery14());
				fxyUser.setContacts(fxyGzgl09.getQuery15());
				fxyUser.setMobile(fxyGzgl09.getQuery16());
				fxyUser.setProvinceCode(getCode(fxyGzgl09.getQuery18()));
				fxyUser.setProvinceName(fxyGzgl09.getQuery18());
				fxyUser.setCityCode(getCode(fxyGzgl09.getQuery20()));
				fxyUser.setCityName(fxyGzgl09.getQuery20());
				fxyUser.setDistrictCode(getCode(fxyGzgl09.getQuery22()));
				fxyUser.setDistrictName(fxyGzgl09.getQuery22());
				fxyUser.setAddress(fxyGzgl09.getQuery23());
				fxyUser.setEmail(fxyGzgl09.getQuery24());
				fxyUser.setThirdAccount(fxyGzgl09.getQuery25());
				String res = fxyUtil.postDeliveryAddress(appCode, redisUtil, fxyUser);
				if (!StringUtil.isEmpty(res)) {
					fxyGzgl09.setQuery26(res);
				}
			}catch (Exception e) {

			}

			//同时生成合同
				if(StringUtil.isEmpty(fxyGzgl09.getQuery27())){
					try{

			fxyUser fxyUser1 = new fxyUser();
				List<FxyGzgl04> list04 = fxyGzgl04Controller.get04by07(fxyGzgl09.getQuery07());
				FxyGzgl04 fxyGzgl04 = list04.get(0);
				    fxyUser1.setCaseNumber(fxyGzgl04.getQuery16());
					fxyUser1.setUserId(fxyGzgl09.getQuery14());
					fxyUser1.setOrgId(fxyGzgl04.getQuery20());
					fxyUser1.setBusinessType(fxyGzgl04.getQuery21());
					fxyUser1.setProcessNumber(fxyGzgl04.getQuery15());
					fxyUser1.setSendAgreement(fxyGzgl04.getQuery19());
					fxyUser1.setAgreementCode(fxyGzgl09.getQuery07()+fxyGzgl09.getQuery16());
					fxyUser1.setTemplateCode("sddzqrs_zd_test_202002_01");
					fxyUser1.setAgreementName("送达地址");
					List<conmap> conlist = new ArrayList();
				List<FxyGzgl05> fxyGzgl05List = new ArrayList<>();
				fxyGzgl05List = fxyGzgl04Controller.get05by0708(fxyGzgl04.getQuery07(), fxyGzgl04.getQuery08());
				List<FxyGzgl02> fxyGzgl02List = new ArrayList<>();
				fxyGzgl02List = fxyGzgl04Controller.get02by0708(fxyGzgl04.getQuery07(), fxyGzgl04.getQuery08());



				String htbl01 = "";//合同编号
				String htbl02 = "";//签署人类型
				String htbl03 = fxyGzgl09.getQuery15();//姓名
				String htbl04 = fxyGzgl09.getQuery18()+fxyGzgl09.getQuery20()+fxyGzgl09.getQuery22()+fxyGzgl09.getQuery23();//地址
				String htbl05 = fxyGzgl09.getQuery15();//收件人
				String htbl06 = fxyGzgl09.getQuery16();//电话
				String htbl07 = fxyGzgl09.getQuery24();//email
				String htbl08 = "";//签署人类型

				for(FxyGzgl05 t05: fxyGzgl05List){
					if("htbl01".equals(t05.getQuery15())){
						htbl01 = t05.getQuery17();
					}
 				}
				for(FxyGzgl02 t02: fxyGzgl02List){
					if(fxyGzgl09.getQuery16().equals(t02.getQuery12())){//手机号一致
						htbl02 = t02.getQuery27();//签署人类型
						htbl08 = t02.getQuery27();//签署人类型
					}
				}
				conmap con01 = new conmap();
				con01.setConKey("htbl01");
				con01.setConValue(htbl01);
				conmap con02 = new conmap();
				con02.setConKey("htbl02");
				con02.setConValue(htbl02);
				conmap con03 = new conmap();
				con03.setConKey("htbl03");
				con03.setConValue(htbl03);
				conmap con04 = new conmap();
				con04.setConKey("htbl04");
				con04.setConValue(htbl04);
				conmap con05 = new conmap();
				con05.setConKey("htbl05");
				con05.setConValue(htbl05);
				conmap con06 = new conmap();
				con06.setConKey("htbl06");
				con06.setConValue(htbl06);
				conmap con07 = new conmap();
				con07.setConKey("htbl07");
				con07.setConValue(htbl07);
				conmap con08 = new conmap();
				con08.setConKey("htbl08");
				con08.setConValue(htbl08);
				conlist.add(con01);
				conlist.add(con02);
				conlist.add(con03);
				conlist.add(con04);
				conlist.add(con05);
				conlist.add(con06);
				conlist.add(con07);
				conlist.add(con08);
					fxyUser1.setConmapList(conlist);
					String userids = fxyGzgl09.getQuery14();
					String signs = fxyGzgl09.getQuery15();
					fxyUser1.setUserIds(userids);
					fxyUser1.setSignatorys(htbl08);//签署方
				agreementres ag =  fxyUtil.addAgreementByProcessNumberreturnobject(appCode,redisUtil,fxyUser1);
						if (!StringUtil.isEmpty(ag.getResultCode())) {
							fxyGzgl09.setQuery27(ag.getResultData().getWritInfos().getWritNumber());//批次编号
						}
		}catch (BaseBusinessException e1){
			return Result.error(e1.getMessage());
		}

				}
		fxyGzgl09Service.save(fxyGzgl09);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl09);
		String id = fxyGzgl09.getId();
		sysDataLogService.addDataLog("fxy_gzgl_09",id,  datacont);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param fxyGzgl09
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FxyGzgl09 fxyGzgl09) {
		if(StringUtil.isEmpty(fxyGzgl09.getQuery39())||fxjConstant.iscommitfxy.equals(fxyGzgl09.getQuery39())) {//不提交法信
			fxyGzgl09Service.updateById(fxyGzgl09);
			return Result.ok("编辑成功!");
		}
		String appCode =  appcode;

		try{
			fxyUser fxyUser = new fxyUser();
			fxyUser.setUserId(fxyGzgl09.getQuery14());
			fxyUser.setContacts(fxyGzgl09.getQuery15());
			fxyUser.setMobile(fxyGzgl09.getQuery16());
			fxyUser.setProvinceCode( getCode(fxyGzgl09.getQuery18()));
			fxyUser.setProvinceName(fxyGzgl09.getQuery18());
			fxyUser.setCityCode(getCode(fxyGzgl09.getQuery20()));
			fxyUser.setCityName(fxyGzgl09.getQuery20());
			fxyUser.setDistrictCode(getCode(fxyGzgl09.getQuery22()));
			fxyUser.setDistrictName(fxyGzgl09.getQuery22());
			fxyUser.setAddress(fxyGzgl09.getQuery23());
			fxyUser.setEmail(fxyGzgl09.getQuery24());
			fxyUser.setThirdAccount(fxyGzgl09.getQuery25());
			String res = fxyUtil.postDeliveryAddress(appCode,redisUtil,fxyUser);
			if(!StringUtil.isEmpty(res)){
				fxyGzgl09.setQuery26(res);
			}
		}catch (BaseBusinessException e){
			fxyGzgl09.setQuery38(e.getMessage());
			fxyGzgl09Service.updateById(fxyGzgl09);
			return Result.error(e.getMessage());
		}
		if(StringUtil.isEmpty(fxyGzgl09.getQuery27())) {

			try {

				//同时生成合同
				fxyUser fxyUser1 = new fxyUser();
				List<FxyGzgl04> list04 = fxyGzgl04Controller.get04by07(fxyGzgl09.getQuery07());
				FxyGzgl04 fxyGzgl04 = list04.get(0);
				fxyUser1.setCaseNumber(fxyGzgl04.getQuery16());
				fxyUser1.setUserId(fxyGzgl09.getQuery14());
				fxyUser1.setOrgId(fxyGzgl04.getQuery20());
				fxyUser1.setBusinessType(fxyGzgl04.getQuery21());
				fxyUser1.setProcessNumber(fxyGzgl04.getQuery15());
				fxyUser1.setSendAgreement(fxyGzgl04.getQuery19());
				fxyUser1.setAgreementCode(fxyGzgl09.getQuery07()+fxyGzgl09.getQuery16());
				fxyUser1.setTemplateCode("sddzqrs_zd_test_202002_01");
				fxyUser1.setAgreementName("送达地址");
				List<conmap> conlist = new ArrayList();
				List<FxyGzgl05> fxyGzgl05List = new ArrayList<>();
				fxyGzgl05List = fxyGzgl04Controller.get05by0708(fxyGzgl04.getQuery07(), fxyGzgl04.getQuery08());
				List<FxyGzgl02> fxyGzgl02List = new ArrayList<>();
				fxyGzgl02List = fxyGzgl04Controller.get02by0708(fxyGzgl04.getQuery07(), fxyGzgl04.getQuery08());


				String htbl01 = "";//合同编号
				String htbl02 = "";//签署人类型
				String htbl03 = fxyGzgl09.getQuery15();//姓名
				String htbl04 = fxyGzgl09.getQuery18() + fxyGzgl09.getQuery20() + fxyGzgl09.getQuery22() + fxyGzgl09.getQuery23();//地址
				String htbl05 = fxyGzgl09.getQuery15();//收件人
				String htbl06 = fxyGzgl09.getQuery16();//电话
				String htbl07 = fxyGzgl09.getQuery24();//email
				String htbl08 = "";//签署人类型

				for (FxyGzgl05 t05 : fxyGzgl05List) {
					if ("htbl01".equals(t05.getQuery15())) {
						htbl01 = t05.getQuery17();
					}
				}
				for (FxyGzgl02 t02 : fxyGzgl02List) {
					if (fxyGzgl09.getQuery16().equals(t02.getQuery12())) {//手机号一致
						htbl02 = t02.getQuery27();//签署人类型
						htbl08 = t02.getQuery27();//签署人类型
					}
				}
				conmap con01 = new conmap();
				con01.setConKey("htbl01");
				con01.setConValue(htbl01);
				conmap con02 = new conmap();
				con02.setConKey("htbl02");
				con02.setConValue(htbl02);
				conmap con03 = new conmap();
				con03.setConKey("htbl03");
				con03.setConValue(htbl03);
				conmap con04 = new conmap();
				con04.setConKey("htbl04");
				con04.setConValue(htbl04);
				conmap con05 = new conmap();
				con05.setConKey("htbl05");
				con05.setConValue(htbl05);
				conmap con06 = new conmap();
				con06.setConKey("htbl06");
				con06.setConValue(htbl06);
				conmap con07 = new conmap();
				con07.setConKey("htbl07");
				con07.setConValue(htbl07);
				conmap con08 = new conmap();
				con08.setConKey("htbl08");
				con08.setConValue(htbl08);
				conlist.add(con01);
				conlist.add(con02);
				conlist.add(con03);
				conlist.add(con04);
				conlist.add(con05);
				conlist.add(con06);
				conlist.add(con07);
				conlist.add(con08);
				fxyUser1.setConmapList(conlist);
				String userids = fxyGzgl09.getQuery14();
				String signs = fxyGzgl09.getQuery15();
				fxyUser1.setUserIds(userids);
				fxyUser1.setSignatorys(signs);
				agreementres ag = fxyUtil.addAgreementByProcessNumberreturnobject(appCode, redisUtil, fxyUser1);
				if (!StringUtil.isEmpty(ag.getResultCode())) {
					fxyGzgl09.setQuery27(ag.getResultData().getWritInfos().getWritNumber());//批次编号
				}
			} catch (BaseBusinessException e) {
				return Result.error(e.getMessage());
			}
		}
		fxyGzgl09Service.updateById(fxyGzgl09);
		Gson gs = new GsonBuilder().serializeNulls().create();
		String datacont = gs.toJson(fxyGzgl09);
		String id = fxyGzgl09.getId();
		sysDataLogService.addDataLog("fxy_gzgl_09",id,  datacont);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		fxyGzgl09Service.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fxyGzgl09Service.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FxyGzgl09 fxyGzgl09 = fxyGzgl09Service.getById(id);
		if(fxyGzgl09==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(fxyGzgl09);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fxyGzgl09
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FxyGzgl09 fxyGzgl09) {
        return super.exportXls(request, fxyGzgl09, FxyGzgl09.class, "送达地址");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FxyGzgl09.class);
    }

    public  String getCode(String name){
		String res = "11";
		try{

			FxyGzgl10 FxyGzgl10 =  fxyGzgl10Service.getbyquery04(name);

			if(FxyGzgl10!=null ){
				res = FxyGzgl10.getQuery03();
			}
		}catch (Exception e){

		}

		return  res;
	}
}
